﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace Wss.DragRaycast
{

    /// <summary>
    /// 射线接收器，判断发射的射线击中了自己，才会触发事件
    /// </summary>
    [AddComponentMenu("DragRaycast/DragRaycastReceiver")]
    public class DragRaycastReceiver : MonoBehaviour, IDragRaycastReceiver
    {

        public string receiveTag = "";

        public UnityEvent onRaycastHit;

        /// <summary>
        /// 判断射线离开的处理
        /// </summary>
        public UnityEvent onRaycastExit;

        public bool isRaycastHit = false;

        public float hitKeepDuration = 0.1f;

        private float _hitKeepDuration = 0.1f;

        private void Awake()
        {
            this._hitKeepDuration = 0;
        }

        public string GetReceiveTag()
        {
            return receiveTag;
        }

        public void OnHitRayCast(RaycastHit hit)
        {
            if (isRaycastHit == false)
            {
                //TODO 可以区分首次射线进入范围
            }

            onRaycastHit?.Invoke();//射线更新
            isRaycastHit = true;
            _hitKeepDuration = hitKeepDuration;
        }

        private void Update()
        {
            if (isRaycastHit == true)
            {
                _hitKeepDuration -= Time.deltaTime;
                if (_hitKeepDuration <= 0)
                {
                    isRaycastHit = false;
                    onRaycastExit?.Invoke();//射线离开
                }

            }

        }

    }

    /// <summary>
    /// DragRaycast的接受器,DragRaycastReceiver 挂着的节点下，会寻找所有
    /// IDragRaycastHandle，并且响应
    /// </summary>
    interface IDragRaycastReceiver
    {
        string GetReceiveTag();
        void OnHitRayCast(RaycastHit hit);
    }

}